package com.cyyl.updater

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.coroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * @author : Android-张康
 * created on: 2021/8/12 11:52
 * description:
 */
class SettingActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)
        val downloadUrlE = findViewById<TextView>(R.id.progress_text)
//        val url = "https://assistant-res.niucoo.cn/game/1624616191520_cn.niucoo.niucooapp_91.apk"
        val downloadUrl =
            "https://fmapp-cos.chinafamilymart.com.cn/image/20210809/1628501171048/fmapp_v2.6.0_2021-08-06_OpenInstall_release_260_jiagu_sign.apk"
        findViewById<View>(R.id.start_download).setOnClickListener {
            lifecycle.coroutineScope.launch {
                AppUpdaterBuilder(this@SettingActivity)
                    .setDownloadUrl(downloadUrl)
                    .setFileName("update.apk")
                    .update().getProgressFlow().collect {
                        when (it.first) {
                            AppUpdater.DOWNLOAD_STATUS_RUNNING -> {
                                downloadUrlE.text = it.second.toString()
                            }
                            AppUpdater.DOWNLOAD_STATUS_SUCCESSFUL -> {
                                downloadUrlE.text = "SUCCESSFUL"
                            }
                            else -> {
                                downloadUrlE.text = "Failure:${it.third}"
                            }
                        }
                    }
            }
        }
        lifecycle.coroutineScope.launch {
            AppUpdater.lastDownloadFlow?.collect {
                if (it.first == -1) {
                    return@collect
                }
                when (it.first) {
                    AppUpdater.DOWNLOAD_STATUS_RUNNING -> {
                        downloadUrlE.text = it.second.toString()
                    }
                    AppUpdater.DOWNLOAD_STATUS_SUCCESSFUL -> {
                        downloadUrlE.text = "SUCCESSFUL"
                    }
                    else -> {
                        downloadUrlE.text = "Failure:${it.third}"
                    }
                }
            }
        }
    }
}